package data;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.DBObject;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
import com.mongodb.MongoOptions;

import entities.Email;

import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

public class EmailData {
	private static Mongo m = null;
	
	private static String name = "email";
	
	private static String dbname = "email_marketing";
	
	private static DB db = null;
	
	private static DBCollection colls = null;
	
	private static EmailData instance = null;
	
	public static void init() {

		if (m == null) {
			
			try {
				//mongo staff.mongohq.com:10064/rewordpress -u
				
				m = new Mongo("ds031978.mongolab.com",31978);
				db = m.getDB(dbname);
				boolean auth = db.authenticate("hoanbn1984", "123456".toCharArray());
				
			} catch (UnknownHostException e) {
				e.printStackTrace();
			} catch (MongoException e) {
				e.printStackTrace();
			}
		}

		db = m.getDB(dbname);
		colls = db.getCollection(name);
	}
	
	public static List<DBObject> list() {
		init();
		
		List<DBObject> emails = new ArrayList<DBObject>();
		
		DBCursor cursor = colls.find();
		
		int i = 0;
		while (cursor.hasNext()) {
			DBObject dbObject = (DBObject) cursor.next();
			
			emails.add(dbObject);
			
		}
		
		return emails;
	}
	
	public static void insert(BasicDBObject email) {
		init();
		colls.insert(email);
	}
	
	public static DBObject get(String _id) {
		init();
		
		BasicDBObject query = new BasicDBObject("_id", _id);
		
		DBObject email = colls.findOne(query);
		
		return email;
		
	}
	
	public static DBObject getByEmail(String emailAddress) {
		init();
		
		BasicDBObject query = new BasicDBObject("email", emailAddress);
		
		DBObject email = colls.findOne(query);
		
		return email;
	}
	
	public static boolean checkEmailExists(String emailAddress) {
		boolean exists = false;
		
		DBObject email = getByEmail(emailAddress);
		
		if (email != null) {
			exists = true;
		}
		
		return exists;
	}
	
	public static void delete(String _id) {
		/*BasicDBObject query = new BasicDBObject("_id", _id);
		colls.dropIndex(query);*/
	}
}